<template>
  <el-container style="min-height: 100vh">

    <el-aside :width="sideWidth + 'px'" style="box-shadow: 2px 0 6px rgb(0 21 41);">
      <el-menu :default-openeds="['1', '3']" style="min-height: 100%; overflow-x: hidden"
               background-color="rgb(48, 65, 86)"
               text-color="#fff"
               active-text-color="#ffd04b"
               :collapse-transition="false"
               :collapse="isCollapse"
      >
        <div style="height: 60px; line-height: 60px; text-align: center">
          <img src="@/assets/logo.png" alt="" style="width: 20px; position: relative; top: 5px; right: 5px">
          <b style="color: white" v-show="logoTextShow">后台管理系统</b>
        </div>
        <el-submenu index="1">
          <template slot="title">
            <i class="el-icon-message"></i>
            <span slot="title">后台主页</span>
          </template>
         <!-- <el-menu-item index="1-0" ><router-link class="routerto" to="/">后台管理主页</router-link></el-menu-item> -->
          <el-menu-item index="1-1" ><router-link class="routerto" to="/goodsManage">商品后台管理</router-link></el-menu-item>
          <el-menu-item index="1-2"><router-link class="routerto" to="/user">用户后台管理</router-link></el-menu-item>
          <el-menu-item index="1-2"><router-link class="routerto" to="/order">订单后台管理</router-link></el-menu-item>
        </el-submenu>
      </el-menu>
    </el-aside>

    <el-container>
      <el-header style="font-size: 12px; border-bottom: 1px solid #ccc; line-height: 60px; display: flex">
        <div style="flex: 1; font-size: 20px">
          <span :class="collapseBtnClass" style="cursor: pointer" @click="collapse"></span>
        </div>
        <el-dropdown style="width: 70px; cursor: pointer">
          <span>ADRIAN</span>
        </el-dropdown>

      </el-header>

      <el-main>
        <div style="margin-bottom: 30px">
          <el-breadcrumb separator="/">
            <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>商品管理</el-breadcrumb-item>
          </el-breadcrumb>
        </div>

        <div style="margin: 10px 0">
          <el-input style="width: 200px" placeholder="请输入商品名称" suffix-icon="el-icon-search" v-model="goodsName"></el-input>
          <el-input style="width: 200px" placeholder="商品大致描述" suffix-icon="el-icon-position" class="ml-5" v-model="goodsDisc"></el-input>
          <el-button class="ml-5" type="primary" @click="load">搜索</el-button>
          <el-button type="warning" @click="reset">重置</el-button>
        </div>

        <div style="margin: 10px 0">
          <el-button type="primary" @click="handleAdd">新增 <i class="el-icon-circle-plus-outline"></i></el-button>
          <el-popconfirm
              class="ml-5"
              confirm-button-text='确定'
              cancel-button-text='我再想想'
              icon="el-icon-info"
              icon-color="red"
              title="您确定批量删除这些数据吗？"
              @confirm="delBatch"
          >
            <el-button type="danger" slot="reference">批量删除 <i class="el-icon-remove-outline"></i></el-button>
          </el-popconfirm>

<!--          导入的设置-->
          <el-upload action="http://localhost:8090/manage/importGoods" :show-file-list="false" accept="xlsx" :on-success="handleExcelImportSuccess" style="display: inline-block">
            <el-button type="primary" class="ml-5">导入 <i class="el-icon-bottom"></i></el-button>
          </el-upload>
          <el-button type="primary" @click="exp">导出 <i class="el-icon-top"></i></el-button>
        </div>

        <el-table :data="tableData" border stripe :header-cell-class-name="headerBg"  @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55"></el-table-column>
          <el-table-column prop="goodsId" label="商品编号" width="80"></el-table-column>
          <el-table-column prop="goodsName" label="商品名称" width="80"></el-table-column>
          <el-table-column prop="goodsPrice" label="商品价格" width="140"></el-table-column>
          <el-table-column prop="goodsStock" label="商品库存" width="140"></el-table-column>
          <el-table-column prop="goodsDisc" label="商品描述" width="120"></el-table-column>
          <el-table-column prop="goodsPrice" label="商品价格"></el-table-column>
          <el-table-column prop="createTime" label="商品创建时间"></el-table-column>
          <el-table-column prop="updateTime" label="商品最近修改时间"></el-table-column>
          <el-table-column prop="isSeckill" label="商品是否参与秒杀活动(参加为1参加为0)"></el-table-column>
          <el-table-column label="操作"  width="200" align="center">
            <template slot-scope="scope">
              <el-button type="success" @click="handleEdit(scope.row)">编辑 <i class="el-icon-edit"></i></el-button>
              <el-popconfirm
                  class="ml-5"
                  confirm-button-text='给我删！'
                  cancel-button-text='再让我想想呗'
                  icon="el-icon-info"
                  icon-color="red"
                  title="您确定删除吗？"
                  @confirm="del(scope.row.goodsId)"
              >
                <el-button type="danger" slot="reference">删除 <i class="el-icon-remove-outline"></i></el-button>
              </el-popconfirm>
              <el-button type="success" @click="handleSeckill(scope.row)">秒杀！</el-button>
            </template>
          </el-table-column>
        </el-table>
        <div style="padding: 10px 0">
          <el-pagination
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              :current-page="pageNum"
              :page-sizes="[3, 5, 10, 20]"
              :page-size="pageSize"
              layout="total, sizes, prev, pager, next, jumper"
              :total="total">
          </el-pagination>
        </div>

        <el-dialog title="商品信息" :visible.sync="dialogFormVisible" width="30%" >
          <el-form label-width="80px" size="small">
            <el-form-item label="商品名">
              <el-input v-model="form.goodsName" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="商品价格">
              <el-input v-model="form.goodsPrice" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="商品库存">
              <el-input v-model="form.goodsStock" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="商品描述">
              <el-input v-model="form.goodsDisc" autocomplete="off"></el-input>
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button @click="dialogFormVisible = false">取 消</el-button>
            <el-button type="primary" @click="save">确 定</el-button>
          </div>
        </el-dialog>


        <el-dialog title="秒杀信息" :visible.sync="dialogFormVisible2" width="30%" >
          <el-form label-width="80px" size="small">
            <el-form-item label="商品编号">
              <el-input v-model="seckillForm.goodsId" autocomplete="off" readonly></el-input>
            </el-form-item>
            <el-form-item label="商品名称">
              <el-input v-model="seckillForm.goodsName" autocomplete="off" readonly></el-input>
            </el-form-item>
            <el-form-item label="活动开始时间">
              <el-input v-model="seckillForm2.startTime" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="活动结束时间">
              <el-input v-model="seckillForm2.endTime" autocomplete="off"></el-input>
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button @click="dialogFormVisible2 = false">取 消</el-button>
            <el-button type="primary" @click="doSeckill">确 定</el-button>
            <el-button type="primary" @click="closeSeckill">活动取消！</el-button>
          </div>
        </el-dialog>


      </el-main>

    </el-container>
  </el-container>
</template>

<script>

// import request from "@/utils/request";
import router from "../../router";
export default {
  
  name: 'Home',
  data() {
    return {
      tableData: [],
      total: 0,
      pageNum: 1,
      pageSize: 3,
      goodsName: "",
      goodsPrice: "",
      goodsDisc: "",
      goodsStock:"",

      form: {},
      seckillForm:{},
      seckillForm2:{},
      dialogFormVisible: false,
      dialogFormVisible2: false,
      multipleSelection: [],
      msg: "hello thh",
      collapseBtnClass: 'el-icon-s-fold',
      isCollapse: false,
      sideWidth: 200,
      logoTextShow: true,
      headerBg: 'headerBg'
    }
  },
  created() {
    // 请求分页查询数据
    this.load()
  },
   mounted() {
    this.cheackAdmin();
  },
  methods: {

     cheackAdmin() {
      this.$axios
        .get("/admin/index", {
          headers: {
            "x-access-token": localStorage.getItem("x-access-token"),
          },
        })
        .then((res) => {
          console.log(res);
          if (res.data.code == 401 && "用户不存在！" == res.data.extend.result) {
            this.$message.error("请先登录再访问后台");
            router.push("/adminpage/login");
          } else if (
            res.data.code == 401 &&
            "登录失败，该用户没有权限" == res.data.extend.result
          ) {
            this.$message.error("登录失败，该用户不是管理员");
              router.push("/adminpage/login");
          }else if (
            res.data.code == 401 &&
            "该用户已被锁定,暂时无法登录！" == res.data.extend.result
          ) {
            this.$message.error("登录失败，该用户不是管理员");
                router.push("/adminpage/login");
          }
          
          else if (
            res.data.code == 200 &&
            "登陆成功" == res.data.extend.result
          ) {
            this.$message({
              message: "管理员你好，欢迎来到后台管理页面",
              type: "success",
            });
            
          }
        });
    },

     //时间转换(js将 “2021-07-06T06:23:57.000+00:00” 转换为年月日时分秒)
    transformTimestamp(timestamp) {
      let a = new Date(timestamp).getTime();
      const date = new Date(a);
      const Y = date.getFullYear() + "-";
      const M =
        (date.getMonth() + 1 < 10
          ? "0" + (date.getMonth() + 1)
          : date.getMonth() + 1) + "-";
      const D =
        (date.getDate() < 10 ? "0" + date.getDate() : date.getDate()) + "  ";
      const h =
        (date.getHours() < 10 ? "0" + date.getHours() : date.getHours()) + ":";
      const m =
        date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes();
      // const s = date.getSeconds(); // 秒
      const dateString = Y + M + D + h + m;
      // console.log('dateString', dateString); // > dateString 2021-07-06 14:23
      return dateString;
    },
    collapse() {  // 点击收缩按钮触发
      this.isCollapse = !this.isCollapse
      if (this.isCollapse) {  // 收缩
        this.sideWidth = 64
        this.collapseBtnClass = 'el-icon-s-unfold'
        this.logoTextShow = false
      } else {   // 展开
        this.sideWidth = 200
        this.collapseBtnClass = 'el-icon-s-fold'
        this.logoTextShow = true
      }
    },
    load() {
      this.request.get("/manage/goodsPage", {
        params: {
          pageNum: this.pageNum,
          pageSize: this.pageSize,
          goodsName: this.goodsName,
          goodsDisc: this.goodsDisc,
        }
      }).then(res => {
        this.tableData = res.records
        this.total = res.total
      })
    },
    save() {
      this.request.post("/manage/saveGoods/", this.form).then(res => {
        if (res==1) {
          this.$message.success("添加成功")
          this.dialogFormVisible = false
          this.load()
        }else if(res==2){
          this.$message.success("编辑成功")
          this.dialogFormVisible = false
          this.load()
        }
        else {
          this.$message.error("操作失败啦~商品名不能重复哦~还有记得填写库存数和商品价格")
        }
      })
    },
    handleAdd() {
      this.dialogFormVisible = true
      this.form = {}
    },
    handleEdit(row) {
      this.form = row
      this.dialogFormVisible = true
    },
    del(goodsId) {
      this.request.delete("/manage/deleteGoods/" + goodsId).then(res => {
        if (res) {
          this.$message.success("删除成功")
          this.load()
        } else {
          this.$message.error("删除失败")
        }
      })
    },
    handleSelectionChange(val) {
      console.log(val)
      this.multipleSelection = val
    },
    delBatch() {
      let goodsIds = this.multipleSelection.map(v => v.goodsId)  // [{}, {}, {}] => [1,2,3]
      this.request.post("/manage/delGoods/batch", goodsIds).then(res => {
        if (res) {
          this.$message.success("批量删除成功")
          this.load()
        } else {
          this.$message.error("批量删除失败")
        }
      })
    },
    reset() {
      this.goodsName = ""
      this.goodsDisc = ""
      this.load()
    },
    handleSizeChange(pageSize) {
      console.log(pageSize)
      this.pageSize = pageSize
      this.load()
    },
    handleCurrentChange(pageNum) {
      console.log(pageNum)
      this.pageNum = pageNum
      this.load()
    },
    //导出
    exp(){
      window.open("http://localhost:8090/manage/exportGoods")
    },
    handleExcelImportSuccess(){
      this.$message.success("文件导入成功啦!")
      this.load()
    },
    //回显当前行对应的秒杀开启和结束时间
    getSeckillTime(row){
      this.request.get("/manage/getSeckillTime",{
        params:{
          goodsId:row.goodsId
        }
      }).then(res=>{
        if(res!=null){
          console.log(res)
          var resData=res;
            resData.startTime=this.transformTimestamp(resData.startTime)+":00";
            resData.endTime=this.transformTimestamp(resData.endTime)+":00";
                  resData.createTime=this.transformTimestamp(resData.createTime)+":00";
            resData.updateTime=this.transformTimestamp(resData.updateTime)+":00";
            console.log(resData)
          this.seckillForm2=resData
        }else{
          this.seckillForm2={
            "startTime":null,
            "endTime":null
          }
        }
      })
    },
    //打开秒杀的设置栏
    handleSeckill(row) {
      this.seckillForm = row
      this.getSeckillTime(row);
      this.dialogFormVisible2 = true
    },
    //秒杀处理业务
    doSeckill() {
      this.request.get("/manage/secKillOpen", {
        params: {
          goodsId: this.seckillForm.goodsId,
          startTime: this.seckillForm2.startTime,
          endTime: this.seckillForm2.endTime,
        }
      }).then(res => {
        if (res.msg!="处理成功") {
          this.$message.error("活动开启失败,已存在秒杀活动啦~")
          this.dialogFormVisible2 = false
          this.load()
        } else {
          this.$message.success("活动开启成功")
          this.dialogFormVisible2 = false
          this.load()
        }
      })
    },
    //关闭秒杀活动事件
    closeSeckill(){
      this.request.get("/manage/secKillClose", {
        params: {
          goodsId: this.seckillForm.goodsId
        }
      }).then(res => {
        if (res) {
          this.$message.success("活动关闭成功")
          this.dialogFormVisible2 = false
          this.load()
        } else {
          this.$message.error("活动关闭失败")
          this.dialogFormVisible2 = false
          this.load()
        }
      })
    }
  }
}
</script>

<style>
.headerBg {
  background: #eee!important;
}
.routerto{
  color: #fff;
  text-decoration: none;

}
</style>
